import { FC, useEffect, useRef, useState } from 'react'
import Taro, { useDidShow, useShareAppMessage } from '@tarojs/taro'
import { AtTabs, AtTabsPane } from 'taro-ui'
import pic2 from '../../resource/pic2.png'
import arrow from '../../resource/arrow.png'
import style from './style.less'
import { Button } from '@tarojs/components'

const Order: FC = () => {
  const [current, setCurrent] = useState(0)
  const tabList = useRef([{ title: '运输中' }, { title: '已完成' }, { title: '已取消' }])

  const [list, setList] = useState<any[]>([])
  const [completeList, setCompleteList] = useState<any[]>([])
  const [cancelList, setCancelList] = useState<any[]>([])

  useEffect(() => {
    if (!Taro.getStorageSync('auth')) {
      return
    }
    if (current === 0) {
      getInTransitReq()
    } else if (current === 1) {
      getCompleteReq()
    } else if (current === 2) {
      getCancelReq()
    }
  }, [current])

  useDidShow(() => {
    if (!Taro.getStorageSync('auth')) {
      return
    }
    if (current === 0) {
      getInTransitReq()
    } else if (current === 1) {
      getCompleteReq()
    } else if (current === 2) {
      getCancelReq()
    }
  })

  useShareAppMessage(res => {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '我正在使用满满运发货，快来试试吧'
    }
  })

  const getInTransitReq = () => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://10.190.84.29:9527/fta-trade/order/shipper/getOrderList',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token')
        // openId: 'zajalahddlalalskdlklashdklahsdly'
      }),
      success: (data) => {
        console.log('运输中订单', data.data);
        setList(data.data.data.orders)
        Taro.hideLoading()
      },
      fail: () => {
        Taro.hideLoading()
        console.log('请求订单失败');
      }
    })
  }

  const getCompleteReq = () => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://10.190.84.29:9527/fta-trade/order/shipper/getCompletedOrders',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token')
        // openId: 'zajalahddlalalskdlklashdklahsdly'
      }),
      success: (data) => {
        console.log('已完成订单', data.data);
        setCompleteList(data.data.data.orders)
        Taro.hideLoading()
      },
      fail: () => {
        Taro.hideLoading()
        console.log('请求订单失败');
      }
    })
  }

  const getCancelReq = () => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://10.190.84.29:9527/fta-trade/order/shipper/getCanceledOrders',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token')
        // openId: 'zajalahddlalalskdlklashdklahsdly'
      }),
      success: (data) => {
        console.log('已取消订单', data.data);
        setCancelList(data.data.data.orders)
        Taro.hideLoading()
      },
      fail: () => {
        Taro.hideLoading()
        console.log('请求订单失败');
      }
    })
  }

  const handleClick = (value) => {
    setCurrent(value)
  }

  const showAgree = (item) => {
    Taro.navigateTo({ url: `/packageC/agreement/index?res=${JSON.stringify(item)}` })
  }

  const cancel = (num, order) => {
    if (num === 1) {
      Taro.showModal({
        title: '提示',
        content: '取消订单后，订金将退还给司机，且会影响您的成交率',
        success: function (res) {
          if (res.confirm) {
            Taro.request({
              url: 'http://10.190.84.29:9527/fta-trade/order/shipper/cancelOrder',
              method: 'POST',
              data: JSON.stringify({
                orderNumber: order,
                openId: Taro.getStorageSync('token')
              }),
              success: () => {
                setCurrent(2)
              },
              fail: () => {
                console.log('取消订单失败');
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else if (num === 2) {
      Taro.showModal({
        title: '提示',
        content: '取消该订单会从您的保证金当中扣除订金金额的50%作为对司机的赔偿，且会影响您的成交率',
        success: function (res) {
          if (res.confirm) {
            Taro.request({
              url: 'http://10.190.84.29:9527/fta-trade/order/shipper/cancelOrder',
              method: 'POST',
              data: JSON.stringify({
                orderNumber: order,
                openId: Taro.getStorageSync('token')
              }),
              success: () => {
                setCurrent(2)
              },
              fail: () => {
                console.log('取消订单失败');
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  }

  const confirmReceipt = (num, order, amount, cargoId, type) => {
    if (num !== 6) {
      return
    }
    Taro.showModal({
      title: '确认货已送达',
      content: '确认收货后，运费将立即转至司机账户',
      success: function (res) {
        if (res.confirm) {
          Taro.navigateTo({ url: `/packageC/payment/index?amount=${amount}&cargoId=${cargoId}&order=${order}&type=${type}` })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }

  const reshelf = (cargoId, orderNumber) => {
    Taro.request({
      url: 'http://10.190.84.29:9527/fta-trade/order/shipper/republishCargo',
      method: 'POST',
      data: JSON.stringify({
        cargoId: cargoId,
        openId: Taro.getStorageSync('token')
      }),
      success: (data) => {
        // console.log(data.data.data.cargoInfo);

        Taro.navigateTo({ url: `/packageB/edit/index?param=${JSON.stringify(data.data.data.cargoInfo)}&orderNumber=${orderNumber}` })
      },
      fail: () => {
        console.log('重新上架失败');
      }
    })
  }

  const getInTransit = () => {
    if (list.length === 0) {
      return (
        <div className="unLogin">
          <img src={pic2} />
          <div>暂无订单～</div>
        </div>
      )
    }
    return (
      <div className="body">
        {
          list.map(item => {
            return (
              <div className="box">
                <div className="areaContainer">
                  <div className="areaItem">{item.loadAddress.substring(item.loadAddress.indexOf('-') + 1, item.loadAddress.indexOf(' '))}</div>
                  <img className="areaItem" src={arrow} alt="" />
                  <div className="areaItem">{item.unloadingAdress.substring(item.unloadingAdress.indexOf('-') + 1, item.unloadingAdress.indexOf(' '))}</div>
                </div>
                <div className="detail" onClick={() => { Taro.navigateTo({ url: `/packageB/orderDetail/index?param=${JSON.stringify(item)}&status=1` }) }}>运单详情 <i>{'>'}</i></div>
                <div>{item.cargoName} ｜ {item.truckLength}米 {item.truckType} ｜ {item.truckWeight}吨 ｜ {item.cargoCapacipy}方</div>
                <div className="amountContainer">
                  {item.status === 1 && <div style={{ color: 'red' }}>待您签订运输协议</div>}
                  {item.status === 2 && <div style={{ color: '#14CD0E' }}>您已签订运输协议</div>}
                  {item.status === 5 && <div style={{ color: '#14CD0E' }}>司机已经完成装货</div>}
                  {item.status === 6 && <div style={{ color: '#14CD0E' }}>司机已经完成卸货</div>}
                  <div>订金：¥{item.driverPayDeposit}</div>
                  <div>运费：¥{item.totalFreightAmount}</div>
                </div>
                {item.isBackDeposit ? <div className="tips">订金将在您<i>点击"确认收货"</i>后立即退还给司机</div> :
                  <div className="tips">订金将在您<i>点击"确认收货"</i>后转至您的账户</div>}
                <div className="btnContainer">
                  <div onClick={() => { showAgree(item) }}>查看协议</div>
                  <div className={item.status === 5 || item.status === 6 ? 'disable' : ''} onClick={() => { cancel(item.status, item.orderNumber) }}>取消订单</div>
                  <div className={item.status === 6 ? '' : 'disable'} onClick={() => { confirmReceipt(item.status, item.orderNumber, item.totalFreightAmount, item.cargoId, 201) }}>确认收货</div>
                </div>
              </div>
            )
          })
        }
      </div>
    )
  }

  const getComplete = () => {
    if (completeList.length === 0) {
      return (
        <div className="unLogin">
          <img src={pic2} />
          <div>暂无订单～</div>
        </div>
      )
    }
    return (
      <div className="body">
        {
          completeList.map(item => {
            return (
              <div className="box" style={{ height: Taro.pxTransform(310) }}>
                <div className="areaContainer">
                  <div className="areaItem">{item.loadAddress.substring(item.loadAddress.indexOf('-') + 1, item.loadAddress.indexOf(' '))}</div>
                  <img className="areaItem" src={arrow} alt="" />
                  <div className="areaItem">{item.unloadingAdress.substring(item.unloadingAdress.indexOf('-') + 1, item.unloadingAdress.indexOf(' '))}</div>
                </div>
                <div className="detail" onClick={() => { Taro.navigateTo({ url: `/packageB/orderDetail/index?param=${JSON.stringify(item)}&status=2` }) }}>运单详情 <i>{'>'}</i></div>
                <div>{item.cargoName} ｜ {item.truckLength}米 {item.truckType} ｜ {item.truckWeight}吨 ｜ {item.cargoCapacipy}方</div>
                <div className="amount">运费：¥{item.totalFreightAmount}</div>
                <div className="btnContainer2">
                  <Button onClick={() => { Taro.navigateTo({ url: '/packageC/evaluate/index' }) }}>去评价</Button>
                  <Button openType="share">分享订单</Button>
                </div>
              </div>
            )
          })
        }
      </div>
    )
  }

  const getCancel = () => {
    if (cancelList.length === 0) {
      return (
        <div className="unLogin">
          <img src={pic2} />
          <div>暂无订单～</div>
        </div>
      )
    }
    return (
      <div className="body">
        {
          cancelList.map(item => {
            return (
              <div className="box" style={{ height: Taro.pxTransform(280) }}>
                <div className="areaContainer">
                  <div className="areaItem">{item.loadAddress.substring(item.loadAddress.indexOf('-') + 1, item.loadAddress.indexOf(' '))}</div>
                  <img className="areaItem" src={arrow} alt="" />
                  <div className="areaItem">{item.unloadingAdress.substring(item.unloadingAdress.indexOf('-') + 1, item.unloadingAdress.indexOf(' '))}</div>
                </div>
                <div className="detail" onClick={() => { Taro.navigateTo({ url: `/packageB/orderDetail/index?param=${JSON.stringify(item)}&status=3` }) }}>运单详情 <i>{'>'}</i></div>
                <div>{item.cargoName} ｜ {item.truckLength}米 {item.truckType} ｜ {item.truckWeight}吨 ｜ {item.cargoCapacipy}方</div>
                <div className="cancelContainer">
                  <div>{item.msg}</div>
                  <div>运费：¥{item.totalFreightAmount}</div>
                </div>
                <div className="reshelf" onClick={() => { reshelf(item.cargoId, item.orderNumber) }}>重新上架</div>
              </div>
            )
          })
        }
      </div>
    )
  }

  return (
    <div className={style.root}>
      <AtTabs current={current} tabList={tabList.current} onClick={handleClick}>
        <div style={{ height: Taro.pxTransform(20) }} />
        <AtTabsPane current={current} index={0} >
          {Taro.getStorageSync('auth') ? getInTransit() :
            <div className="unLogin">
              <img src={pic2} />
              <div>暂无订单～</div>
            </div>}
        </AtTabsPane>
        <AtTabsPane current={current} index={1}>
          {Taro.getStorageSync('auth') ? getComplete() :
            <div className="unLogin">
              <img src={pic2} />
              <div>暂无订单～</div>
            </div>
          }
        </AtTabsPane>
        <AtTabsPane current={current} index={2}>
          {Taro.getStorageSync('auth') ? getCancel() :
            <div className="unLogin">
              <img src={pic2} />
              <div>暂无订单～</div>
            </div>
          }
        </AtTabsPane>
      </AtTabs>

    </div>
  )
}

export default Order